<template>
  <div class="cover__module">
    <label :class="['image-slot__item',{'upload-image-border':isBorder}]" for="cover-upload-btn" slot="error">
      <el-image :src="useImage" class="cover__item" fit="cover">
        <div class="image-slot__item" slot="error" />
      </el-image>
      <input :accept="accept" @change="checkFileHandler" class="item-uploader" id="cover-upload-btn" type="file" v-show="false" />
      <loadingModule tip="上传中" v-if="loading" />
    </label>
    <ul class="upload-cover-suggest">
      <li>建议上传高清封面 960 * 540</li>
      <li>合适的封面有助于增加稿件曝光,请务必上传</li>
    </ul>
    <cutImageModule :image="imageFile" @cancel="cutImageModuleShow = false" @cutComplete="cutCompleteHandler" title="设置音频稿件封面" v-if="cutImageModuleShow" />
  </div>
</template>

<script>
import cutImageModule from "@/components/CutCoverModule/index.vue";
import loadingModule from "@/components/Loading/index.vue";

export default {
    name: "AudioArchiveCoverModule",
    components: {
        cutImageModule,
        loadingModule,
    },
    props: {
        loading: {
            type: [String, Boolean],
            default: false,
        },
        cover: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            accept: "image/jpeg, image/jpg, image/png, image/bmp",
            newCover: "",
            imageFile: null,
            cutImageModuleShow: false,
        };
    },
    computed: {
        useImage() {
            return this.newCover || this.cover;
        },
        isBorder() {
            return !this.useImage;
        },
    },
    methods: {
        checkFileHandler(evt) {
            const [file] = evt.target.files;
            if (!this.verifyFile(file)) {
                this.$message.error("文件格式不正确!");
                return;
            }
            this.imageFile = file;
            this.cutImageModuleShow = true; // 选择文件 弹出图片剪裁框
            evt.target.value = null;
        },
        verifyFile(file) {
            return file.type && this.accept.indexOf(file.type) !== -1;
        },
        previewCover(file) {
            try {
                const blob = window.URL.createObjectURL(file);
                this.newCover = blob;
            } catch (error) {
                this.newCover = file;
            }
        },
        cutCompleteHandler({ blob, file }) {
            this.cutImageModuleShow = false;
            this.previewCover(blob);
            this.$emit("change", file); // 这里给它父级抛出去图片文件
        },
    },
};
</script>

<style lang="scss" scoped>
.cover__module {
  .cover__item {
    border-radius: 4px;
  }
  .image-slot__item {
    height: 130px;
    width: 130px * (16 / 10);
    display: block;
    position: relative;
    border-radius: 4px;
    background: url(~@/assets/images/audio_cover.png) no-repeat center;
    cursor: pointer;
    overflow: hidden;
    .cover__item {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
